<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据库配置</title>
    <!-- 引入 Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入 Font Awesome 图标 -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 自定义 Tailwind 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#1677ff', // 主色调，类似截图中的蓝色
                        lightBg: '#f5f7fa', // 浅背景色
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                },
            }
        }
    </script>
    <!-- 自定义工具类 -->
    <style>
        .content-auto {
            content-visibility: auto;
        }

        .sidebar-item {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.75rem 1rem;
            border-radius: 0.375rem;
            cursor: pointer;
            transition: all 200ms;
            margin-bottom: 0.5rem;
        }

        .sidebar-item.active {
            background-color: #1677ff;
            color: white;
        }
        
        .input-error:focus {
            border-color: #ef4444 !important;
            ring-color: #ef4444 !important;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        #message {
            animation: fadeIn 0.3s ease-out;
        }
    </style>
</head>

<body class="bg-lightBg min-h-screen flex flex-col">
    <!-- 顶部导航 -->
    <header class="bg-white shadow-sm p-4">
        <div class="container mx-auto flex justify-between items-center">
            <div class="flex items-center space-x-2">
                <i class="fa fa-cloud-upload text-primary text-2xl"></i>
                <h1 class="text-xl font-bold text-gray-800">文档上传系统</h1>
            </div>
            <div class="flex items-center space-x-4">
                <span class="text-gray-600" id="usernameDisplay">管理员</span>
            </div>
        </div>
    </header>

    <!-- 主要内容 -->
    <div class="flex flex-1">
        <!-- 侧边栏 -->
        <aside class="w-64 bg-white shadow-md">
            <div class="p-4">
                <h1 class="text-2xl font-bold text-gray-800 text-center">会员中心</h1>
                <div class="flex items-center justify-center mt-2">
                    <i class="fa fa-user-circle-o text-primary mr-2"></i>
                    <p class="text-gray-800 font-medium" id="sidebarUsername">13378091517</p>
                </div>
            </div>
            <nav class="mt-4">
                <ul>
                    <li>
                        <a href="index.html" class="sidebar-item">
                            <i class="fa fa-cloud-upload"></i>
                            上传文档
                        </a>
                    </li>
                    <!-- 新增：文档管理 菜单项 -->
                    <li>
                        <a href="documents.html" class="sidebar-item" id="documentsLink">
                            <i class="fa fa-folder-open"></i> <!-- 使用文件夹打开图标，与文档管理语义匹配 -->
                            文档管理
                        </a>
                    </li>
                    <!-- 新增：公众号管理 菜单项 -->
                    <li>
                        <a href="wechat-accounts.html" class="sidebar-item">
                            <i class="fa fa-weixin"></i>
                            公众号管理
                        </a>
                    </li>
                    <!-- 新增：账号管理 菜单项 -->
                    <li>
                        <a href="wechat-account-management.html" class="sidebar-item">
                            <i class="fa fa-user-circle-o"></i>
                            账号管理
                        </a>
                    </li>
                    <!-- 新增：抓取管理 菜单项 -->
                    <li>
                        <a href="scraping.html" class="sidebar-item">
                            <i class="fa fa-scissors"></i>
                            抓取管理
                        </a>
                    </li>
                    <!-- 新增：数据库配置 菜单项 -->
                <li>
                    <a href="database-config.html" class="sidebar-item active">
                        <i class="fa fa-database"></i>
                        数据库配置
                    </a>
                </li>
                <!-- 新增：发布管理 菜单项 -->
                <li>
                    <a href="publish-management.html" class="sidebar-item">
                        <i class="fa fa-paper-plane"></i>
                        发布管理
                    </a>
                </li>
                    <li>
                        <a href="#" class="sidebar-item" id="logoutLink">
                            <i class="fa fa-sign-out"></i>
                            退出登录
                        </a>
                    </li>
                </ul>
            </nav>
        </aside>

        <!-- 主内容区 -->
        <main class="flex-1 p-8">
            <div class="bg-white rounded-lg shadow-sm p-6 max-w-3xl mx-auto">
                <h2 class="text-xl font-semibold text-gray-800 mb-6">数据库配置</h2>

                <!-- 提示消息区域 -->
                <div id="message" class="mb-4 px-4 py-2 rounded-md hidden"></div>
                
                <!-- 环境选择器 -->
                <div class="bg-blue-50 p-4 rounded-md mb-6">
                    <h3 class="text-lg font-medium text-gray-700 mb-3 flex items-center">
                        <i class="fa fa-server text-primary mr-2"></i>环境选择
                    </h3>
                    <div class="flex space-x-4">
                        <div class="flex items-center">
                            <input type="radio" id="testEnv" name="environment" value="test" class="h-4 w-4 text-primary">
                            <label for="testEnv" class="ml-2 block text-sm text-gray-700">测试环境</label>
                        </div>
                        <div class="flex items-center">
                            <input type="radio" id="prodEnv" name="environment" value="prod" class="h-4 w-4 text-primary">
                            <label for="prodEnv" class="ml-2 block text-sm text-gray-700">正式环境</label>
                        </div>
                        <button type="button" id="switchEnvBtn" class="ml-auto px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors text-sm">
                            切换环境
                        </button>
                    </div>
                    <div class="mt-2 text-sm text-gray-500">
                        当前环境: <span id="currentEnvironment" class="font-medium">未设置</span>
                    </div>
                </div>

                <!-- 数据库配置表单 -->
                <form id="databaseConfigForm" class="space-y-6">
                    <!-- 数据库基本信息 -->
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label for="driver" class="block text-sm font-medium text-gray-700 mb-2">
                                驱动类 <span class="text-red-500">*</span>
                            </label>
                            <input type="text" id="driver" name="driver"
                                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                                placeholder="例如: com.mysql.cj.jdbc.Driver">
                        </div>
                        <div>
                            <label for="url" class="block text-sm font-medium text-gray-700 mb-2">
                                数据库URL <span class="text-red-500">*</span>
                            </label>
                            <input type="text" id="url" name="url"
                                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                                placeholder="例如: jdbc:mysql://localhost:3306/testdb">
                            <p class="mt-1 text-xs text-gray-500">格式: jdbc:mysql://主机名:端口号/数据库名</p>
                        </div>
                        <div>
                            <label for="username" class="block text-sm font-medium text-gray-700 mb-2">
                                用户名 <span class="text-red-500">*</span>
                            </label>
                            <input type="text" id="username" name="username"
                                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                                placeholder="数据库用户名">
                        </div>
                        <div>
                            <label for="password" class="block text-sm font-medium text-gray-700 mb-2">
                                密码
                            </label>
                            <input type="password" id="password" name="password"
                                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                                placeholder="数据库密码">
                        </div>
                    </div>
                     
                    <!-- 数据库连接池配置 -->
                    <div class="pt-4">
                        <h3 class="text-lg font-medium text-gray-700 mb-4 flex items-center">
                            <i class="fa fa-sliders text-primary mr-2"></i>连接池配置
                        </h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label for="initialSize" class="block text-sm font-medium text-gray-700 mb-2">
                                    初始连接数
                                </label>
                                <input type="number" id="initialSize" name="initialSize" min="1" max="100"
                                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                                    placeholder="默认: 5">
                            </div>
                            <div>
                                <label for="maxActive" class="block text-sm font-medium text-gray-700 mb-2">
                                    最大连接数
                                </label>
                                <input type="number" id="maxActive" name="maxActive" min="1" max="500"
                                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                                    placeholder="默认: 20">
                            </div>
                            <div>
                                <label for="maxIdle" class="block text-sm font-medium text-gray-700 mb-2">
                                    最大空闲连接数
                                </label>
                                <input type="number" id="maxIdle" name="maxIdle" min="1" max="200"
                                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                                    placeholder="默认: 10">
                            </div>
                            <div>
                                <label for="minIdle" class="block text-sm font-medium text-gray-700 mb-2">
                                    最小空闲连接数
                                </label>
                                <input type="number" id="minIdle" name="minIdle" min="1" max="100"
                                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                                    placeholder="默认: 5">
                            </div>
                            <div>
                                <label for="imageAnalysisApi" class="block text-sm font-medium text-gray-700 mb-2">
                                    图片解析API地址
                                </label>
                                <input type="text" id="imageAnalysisApi" name="imageAnalysisApi"
                                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                                    placeholder="例如: http://127.0.0.1:50000">
                            </div>
                            <div>
                                <label for="qrcodeDomain" class="block text-sm font-medium text-gray-700 mb-2">
                                    二维码地址域名
                                </label>
                                <input type="text" id="qrcodeDomain" name="qrcodeDomain"
                                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                                    placeholder="例如: testdoc2.didaproject.com">
                            </div>
                        </div>
                    </div>
                     
                    <!-- 历史配置记录 -->
                    <div class="pt-4 border-t border-gray-200">
                        <h3 class="text-lg font-medium text-gray-700 mb-3 flex items-center">
                            <i class="fa fa-history text-primary mr-2"></i>历史配置
                        </h3>
                        <div class="bg-gray-50 p-4 rounded-md">
                            <p class="text-sm text-gray-500 mb-2">最近使用的配置:</p>
                            <div id="recentConfigs" class="flex flex-wrap gap-2">
                                <!-- 历史配置记录将通过JavaScript动态生成 -->
                                <span class="text-sm text-gray-500">暂无历史记录</span>
                            </div>
                        </div>
                    </div>
                     
                    <!-- 按钮区域 -->
                    <div class="pt-4 flex justify-end space-x-4">
                        <button type="button" id="resetBtn"
                            class="px-4 py-2 border border-gray-300 text-gray-700 rounded-md hover:bg-gray-50 transition-colors">
                            重置
                        </button>
                        <button type="button" id="testConnectionBtn"
                            class="px-4 py-2 border border-primary text-primary rounded-md hover:bg-primary/5 transition-colors flex items-center">
                            <i class="fa fa-check-circle mr-1"></i> 测试连接
                        </button>
                        <button type="submit"
                            class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors flex items-center">
                            <i class="fa fa-save mr-1"></i> 保存配置
                        </button>
                    </div>
                </form>
            </div>
        </main>
    </div>

    <!-- JavaScript 逻辑 -->
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const form = document.getElementById('databaseConfigForm');
            const testConnectionBtn = document.getElementById('testConnectionBtn');
            const resetBtn = document.getElementById('resetBtn');
            const messageDiv = document.getElementById('message');
            const recentConfigsDiv = document.getElementById('recentConfigs');
            let originalConfig = null; // 存储初始配置，用于重置功能

            // 加载当前环境
            loadCurrentEnvironment();
            // 加载当前环境的配置
            loadCurrentConfig();
            // 设置默认值，确保输入框始终显示值
            document.getElementById('imageAnalysisApi').value = document.getElementById('imageAnalysisApi').value || '50000';
            // 设置二维码域名默认值
            document.getElementById('qrcodeDomain').value = document.getElementById('qrcodeDomain').value || (document.getElementById('testEnv').checked ? 'testdoc2.didaproject.com' : 'www.didaidea.com');
            // 加载历史配置
            loadHistoryConfigs();
            
            // 环境切换按钮点击处理
            document.getElementById('switchEnvBtn').addEventListener('click', function() {
                switchEnvironment();
            });

            // 表单提交处理
            form.addEventListener('submit', function (e) {
                e.preventDefault();
                saveDatabaseConfig();
            });

            // 测试连接按钮点击处理
            testConnectionBtn.addEventListener('click', function () {
                testDatabaseConnection();
            });

            // 重置按钮点击处理
            resetBtn.addEventListener('click', function () {
                resetForm();
            });

            // 添加输入验证事件监听
            form.querySelectorAll('input').forEach(input => {
                input.addEventListener('blur', function () {
                    if (this.value.trim() !== '') {
                        validateInput(this);
                    }
                });
            });

            // 加载当前环境
            function loadCurrentEnvironment() {
                showLoading(true);
                fetch('/api/environment-config', {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                    .then(response => response.json())
                    .then(result => {
                        if (result.error) {
                            showMessage('加载环境信息失败: ' + result.error, 'error');
                        } else {
                            const currentEnv = result.currentEnvironment;
                            document.getElementById('currentEnvironment').textContent = 
                                currentEnv === 'test' ? '测试环境' : currentEnv === 'prod' ? '正式环境' : '未设置';
                            
                            // 设置选中的环境
                            if (currentEnv === 'test') {
                                document.getElementById('testEnv').checked = true;
                            } else if (currentEnv === 'prod') {
                                document.getElementById('prodEnv').checked = true;
                            }
                            
                            // 页面加载完成后自动触发环境切换，确保配置正确
                            setTimeout(() => {
                                switchEnvironment();
                            }, 500);
                        }
                    })
                    .catch(error => {
                        showMessage('加载环境信息失败: ' + error.message, 'error');
                        console.error('加载环境信息失败:', error);
                    })
                    .finally(() => {
                        showLoading(false);
                    });
            }
            
            // 切换环境
            function switchEnvironment() {
                const selectedEnv = document.querySelector('input[name="environment"]:checked');
                if (!selectedEnv) {
                    showMessage('请选择要切换的环境', 'error');
                    return;
                }
                
                const targetEnv = selectedEnv.value;
                showLoading(true);
                
                fetch('/api/environment-config?action=switchEnvironment&environment=' + targetEnv, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                    .then(response => response.json())
                    .then(result => {
                        if (result.success) {
                            showMessage('环境切换成功！当前环境: ' + (targetEnv === 'test' ? '测试环境' : '正式环境'), 'success');
                            document.getElementById('currentEnvironment').textContent = targetEnv === 'test' ? '测试环境' : '正式环境';
                            
                            // 直接使用返回的数据更新表单，不再发送额外请求
                            if (result.databaseConfig) {
                                // 保存原始配置，用于重置
                                originalConfig = { 
                                    databaseConfig: result.databaseConfig, 
                                    currentEnvironment: result.currentEnvironment 
                                };
                                
                                // 填充表单 - 从返回的databaseConfig中提取需要的字段
                                document.getElementById('driver').value = result.databaseConfig['driver'] || '';
                                document.getElementById('url').value = result.databaseConfig['url'] || '';
                                document.getElementById('username').value = result.databaseConfig['username'] || '';
                                document.getElementById('password').value = result.databaseConfig['password'] || '';
                                document.getElementById('initialSize').value = result.databaseConfig['initialSize'] || '5';
                                document.getElementById('maxActive').value = result.databaseConfig['maxActive'] || '20';
                                document.getElementById('maxIdle').value = result.databaseConfig['maxIdle'] || '10';
                                document.getElementById('minIdle').value = result.databaseConfig['minIdle'] || '5';
                                
                                // 处理imageAnalysisApi，保留完整URL
                                let apiValue = result.databaseConfig['imageAnalysisApi'] || '';
                                document.getElementById('imageAnalysisApi').value = apiValue || 'http://127.0.0.1:50000';
                                // 处理二维码域名
                                document.getElementById('qrcodeDomain').value = result.databaseConfig['qrcodeDomain'] || (targetEnv === 'test' ? 'testdoc2.didaproject.com' : 'www.didaidea.com');
                                
                                console.log('环境切换完成，已使用返回的配置更新表单');
                            }
                        } else {
                            showMessage('环境切换失败: ' + result.error, 'error');
                        }
                    })
                    .catch(error => {
                        showMessage('环境切换失败: ' + error.message, 'error');
                        console.error('环境切换失败:', error);
                    })
                    .finally(() => {
                        showLoading(false);
                    });
            }
            
            // 加载当前配置
            function loadCurrentConfig() {
                showLoading(true);
                fetch('/api/environment-config', {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                    .then(response => response.json())
                    .then(result => {
                        if (result.error) {
                            showMessage('加载配置失败: ' + result.error, 'error');
                        } else {
                            // 从嵌套的databaseConfig对象中获取配置
                            const config = result.databaseConfig || {};
                            
                            // 保存原始配置，用于重置
                            originalConfig = { databaseConfig: config, currentEnvironment: result.currentEnvironment };
                            
                            // 填充表单 - 从databaseConfig中提取需要的字段
                            document.getElementById('driver').value = config['driver'] || '';
                            document.getElementById('url').value = config['url'] || '';
                            document.getElementById('username').value = config['username'] || '';
                            document.getElementById('password').value = config['password'] || '';
                            document.getElementById('initialSize').value = config['initialSize'] || '5';
                            document.getElementById('maxActive').value = config['maxActive'] || '20';
                            document.getElementById('maxIdle').value = config['maxIdle'] || '10';
                            document.getElementById('minIdle').value = config['minIdle'] || '5';
                            // 使用完整的图片解析API URL，不提取端口号
                            let apiValue = config['imageAnalysisApi'] || '';
                            document.getElementById('imageAnalysisApi').value = apiValue || 'http://127.0.0.1:50000';
                        }
                    })
                    .catch(error => {
                        showMessage('加载配置失败: ' + error.message, 'error');
                        console.error('加载配置失败:', error);
                    })
                    .finally(() => {
                        showLoading(false);
                    });
            }

            // 测试数据库连接
            function testDatabaseConnection() {
                const config = getFormConfig();

                // 验证必填字段
                if (!validateConfig(config)) {
                    return;
                }

                showLoading(true);
                // 添加连接超时处理
                const controller = new AbortController();
                const timeoutId = setTimeout(() => controller.abort(), 10000); // 10秒超时
                
                // 创建包含jdbc前缀的配置对象，确保后端能正确识别
                const jdbcConfig = {
                    'jdbc.driver': config.driver,
                    'jdbc.url': config.url,
                    'jdbc.username': config.username,
                    'jdbc.password': config.password,
                    'jdbc.initialSize': config.initialSize,
                    'jdbc.maxActive': config.maxActive,
                    'jdbc.maxIdle': config.maxIdle,
                    'jdbc.minIdle': config.minIdle
                };
                
                fetch('/api/environment-config?action=testConnection', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(jdbcConfig),
                    signal: controller.signal
                })
                    .then(response => {
                        clearTimeout(timeoutId);
                        // 无论响应状态如何，都尝试解析JSON
                        return response.json().catch(() => {
                            // 如果JSON解析失败，返回默认的错误对象
                            return { 
                                success: false, 
                                message: '服务器响应格式错误: ' + response.statusText 
                            };
                        }).then(data => {
                            // 将响应状态传递给下一个then
                            return { status: response.status, data: data };
                        });
                    })
                    .then(({ status, data }) => {
                        // 即使status不为2xx，也尝试处理响应数据
                        if (data.success) {
                            showMessage(data.message || '数据库连接测试成功!', 'success');
                            // 为成功的测试添加到历史记录
                            saveToHistory(config);
                            loadHistoryConfigs();
                        } else {
                            // 显示具体的错误信息，包括建议
                            let errorMessage = data.message || '数据库连接失败';
                            if (data.suggestion) {
                                errorMessage += '\n' + data.suggestion;
                            }
                            showMessage(errorMessage, 'error');
                        }
                    })
                    .catch(error => {
                        clearTimeout(timeoutId);
                        if (error.name === 'AbortError') {
                            showMessage('连接测试超时，请检查网络或数据库设置', 'error');
                        } else {
                            // 尝试从error中获取更多信息
                            let errorMessage = '连接测试失败';
                            if (error.message) {
                                errorMessage += ': ' + error.message;
                            }
                            showMessage(errorMessage, 'error');
                        }
                        console.error('连接测试失败:', error);
                    })
                    .finally(() => {
                        showLoading(false);
                    });
            }

            // 保存数据库配置
            function saveDatabaseConfig() {
                const config = getFormConfig();

                // 验证必填字段
                if (!validateConfig(config)) {
                    return;
                }

                showLoading(true);
                
                // 使用新的API路径，但保留原有的功能参数
                fetch('/api/environment-config?action=saveEnvironmentConfig', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(config)
                })
                    .then(response => response.json())
                    .then(result => {
                        if (result.success) {
                            showMessage('配置保存成功!', 'success');
                            // 保存到历史记录
                            saveToHistory(config);
                            // 重新加载配置以确保显示最新的配置
                            loadCurrentConfig();
                        } else {
                            showMessage('保存失败: ' + result.message, 'error');
                        }
                    })
                    .catch(error => {
                        showMessage('保存配置失败: ' + error.message, 'error');
                        console.error('保存配置失败:', error);
                    })
                    .finally(() => {
                        showLoading(false);
                    });
            }

            // 从表单获取配置
            function getFormConfig() {
                let imageAnalysisApi = document.getElementById('imageAnalysisApi').value.trim();
                // 确保URL格式正确
                if (imageAnalysisApi && !imageAnalysisApi.startsWith('http://')) {
                    imageAnalysisApi = 'http://' + imageAnalysisApi;
                }
                
                // 获取二维码域名
                let qrcodeDomain = document.getElementById('qrcodeDomain').value.trim();
                // 如果未输入，根据当前环境设置默认值
                if (!qrcodeDomain) {
                    const isTestEnv = document.getElementById('testEnv').checked;
                    qrcodeDomain = isTestEnv ? 'testdoc2.didaproject.com' : 'www.didaidea.com';
                }
                
                return {
                    driver: document.getElementById('driver').value.trim(),
                    url: document.getElementById('url').value.trim(),
                    username: document.getElementById('username').value.trim(),
                    password: document.getElementById('password').value,
                    initialSize: document.getElementById('initialSize').value.trim(),
                    maxActive: document.getElementById('maxActive').value.trim(),
                    maxIdle: document.getElementById('maxIdle').value.trim(),
                    minIdle: document.getElementById('minIdle').value.trim(),
                    imageAnalysisApi: imageAnalysisApi,
                    qrcodeDomain: qrcodeDomain
                };
            }

            // 验证配置
            function validateConfig(config) {
                let isValid = true;
                
                // 清除所有验证错误状态
                clearValidationErrors();
                
                if (!config.driver) {
                    showValidationError('driver', '驱动类不能为空');
                    isValid = false;
                }
                if (!config.url) {
                    showValidationError('url', '数据库URL不能为空');
                    isValid = false;
                } else if (!isValidJdbcUrl(config.url)) {
                    showValidationError('url', '数据库URL格式不正确');
                    isValid = false;
                }
                if (!config.username) {
                    showValidationError('username', '用户名不能为空');
                    isValid = false;
                }
                
                // 连接池参数验证
                if (config.initialSize && isNaN(parseInt(config.initialSize))) {
                    showValidationError('initialSize', '初始连接数必须为数字');
                    isValid = false;
                }
                if (config.maxActive && isNaN(parseInt(config.maxActive))) {
                    showValidationError('maxActive', '最大连接数必须为数字');
                    isValid = false;
                }
                if (config.maxIdle && isNaN(parseInt(config.maxIdle))) {
                    showValidationError('maxIdle', '最大空闲连接数必须为数字');
                    isValid = false;
                }
                if (config.minIdle && isNaN(parseInt(config.minIdle))) {
                    showValidationError('minIdle', '最小空闲连接数必须为数字');
                    isValid = false;
                }
                
                // 检查连接池参数范围
                if (config.initialSize && (parseInt(config.initialSize) < 1 || parseInt(config.initialSize) > 100)) {
                    showValidationError('initialSize', '初始连接数必须在1-100之间');
                    isValid = false;
                }
                if (config.maxActive && (parseInt(config.maxActive) < 1 || parseInt(config.maxActive) > 500)) {
                    showValidationError('maxActive', '最大连接数必须在1-500之间');
                    isValid = false;
                }
                if (config.maxIdle && (parseInt(config.maxIdle) < 1 || parseInt(config.maxIdle) > 200)) {
                    showValidationError('maxIdle', '最大空闲连接数必须在1-200之间');
                    isValid = false;
                }
                if (config.minIdle && (parseInt(config.minIdle) < 1 || parseInt(config.minIdle) > 100)) {
                    showValidationError('minIdle', '最小空闲连接数必须在1-100之间');
                    isValid = false;
                }
                
                if (!isValid) {
                    // 滚动到第一个错误输入
                    const firstError = document.querySelector('.input-error');
                    if (firstError) {
                        firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    }
                }
                
                return isValid;
            }

            // 单个输入验证
            function validateInput(input) {
                const id = input.id;
                const value = input.value.trim();
                
                // 清除之前的错误
                clearValidationError(id);
                
                // 针对不同字段的验证
                if (id === 'driver' && !value) {
                    showValidationError(id, '驱动类不能为空');
                } else if (id === 'url') {
                    if (!value) {
                        showValidationError(id, '数据库URL不能为空');
                    } else if (!isValidJdbcUrl(value)) {
                        showValidationError(id, '数据库URL格式不正确');
                    }
                } else if (id === 'username' && !value) {
                    showValidationError(id, '用户名不能为空');
                } else if (['initialSize', 'maxActive', 'maxIdle', 'minIdle'].includes(id)) {
                    if (value && isNaN(parseInt(value))) {
                        showValidationError(id, '必须输入数字');
                    } else if (value) {
                        const num = parseInt(value);
                        const limits = {
                            initialSize: { min: 1, max: 100 },
                            maxActive: { min: 1, max: 500 },
                            maxIdle: { min: 1, max: 200 },
                            minIdle: { min: 1, max: 100 }
                        };
                        if (num < limits[id].min || num > limits[id].max) {
                            showValidationError(id, `必须在${limits[id].min}-${limits[id].max}之间`);
                        }
                    }
                }
            }

            // 显示验证错误
            function showValidationError(fieldId, message) {
                const input = document.getElementById(fieldId);
                const container = input.parentElement;
                
                // 添加错误样式
                input.classList.add('input-error', 'border-red-500');
                
                // 检查是否已有错误消息
                let errorElement = container.querySelector('.error-message');
                if (!errorElement) {
                    errorElement = document.createElement('p');
                    errorElement.className = 'error-message text-xs text-red-500 mt-1';
                    container.appendChild(errorElement);
                }
                
                errorElement.textContent = message;
            }

            // 清除单个验证错误
            function clearValidationError(fieldId) {
                const input = document.getElementById(fieldId);
                if (input) {
                    input.classList.remove('input-error', 'border-red-500');
                    const container = input.parentElement;
                    const errorElement = container.querySelector('.error-message');
                    if (errorElement) {
                        errorElement.remove();
                    }
                }
            }

            // 清除所有验证错误
            function clearValidationErrors() {
                form.querySelectorAll('.input-error').forEach(input => {
                    input.classList.remove('input-error', 'border-red-500');
                });
                form.querySelectorAll('.error-message').forEach(el => {
                    el.remove();
                });
            }

            // 检查JDBC URL格式
            function isValidJdbcUrl(url) {
                // 支持常见数据库的JDBC URL格式
                const jdbcRegex = /^(jdbc:\w+:\/\/.+)$/;
                return jdbcRegex.test(url);
            }

            // 显示消息
            function showMessage(message, type = 'info') {
                messageDiv.textContent = message;
                messageDiv.classList.remove('hidden', 'bg-green-100', 'text-green-800', 'bg-red-100', 'text-red-800', 'bg-blue-100', 'text-blue-800');

                if (type === 'success') {
                    messageDiv.classList.add('bg-green-100', 'text-green-800');
                    // 成功消息添加动画效果
                    messageDiv.classList.add('animate-pulse');
                    setTimeout(() => {
                        messageDiv.classList.remove('animate-pulse');
                    }, 1000);
                } else if (type === 'error') {
                    messageDiv.classList.add('bg-red-100', 'text-red-800');
                } else {
                    messageDiv.classList.add('bg-blue-100', 'text-blue-800');
                }

                // 5秒后自动隐藏消息
                setTimeout(() => {
                    // 添加淡出动画
                    messageDiv.classList.add('opacity-0', 'transition-opacity', 'duration-500');
                    setTimeout(() => {
                        messageDiv.classList.add('hidden');
                        messageDiv.classList.remove('opacity-0', 'transition-opacity', 'duration-500');
                    }, 500);
                }, 5000);
            }

            // 显示/隐藏加载状态
            function showLoading(show) {
                // 禁用/启用按钮
                form.querySelectorAll('button').forEach(btn => {
                    btn.disabled = show;
                    if (show) {
                        btn.classList.add('opacity-70', 'cursor-not-allowed');
                    } else {
                        btn.classList.remove('opacity-70', 'cursor-not-allowed');
                    }
                });

                // 禁用/启用输入框
                form.querySelectorAll('input').forEach(input => {
                    input.disabled = show;
                    if (show) {
                        input.classList.add('opacity-70', 'cursor-not-allowed');
                    } else {
                        input.classList.remove('opacity-70', 'cursor-not-allowed');
                    }
                });

                // 更新测试连接按钮文本和图标
                if (show && testConnectionBtn.textContent.includes('测试连接')) {
                    testConnectionBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-1"></i> 测试中...';
                } else if (!show && testConnectionBtn.innerHTML.includes('测试中')) {
                    testConnectionBtn.innerHTML = '<i class="fa fa-check-circle mr-1"></i> 测试连接';
                }
            }

            // 重置表单到原始配置
            function resetForm() {
                if (originalConfig) {
                    // 清除验证错误
                    clearValidationErrors();
                    
                    // 重置表单值
                    document.getElementById('driver').value = originalConfig.driver || '';
                    document.getElementById('url').value = originalConfig.url || '';
                    document.getElementById('username').value = originalConfig.username || '';
                    document.getElementById('password').value = originalConfig.password || '';
                    document.getElementById('initialSize').value = originalConfig.initialSize || '5';
                    document.getElementById('maxActive').value = originalConfig.maxActive || '20';
                    document.getElementById('maxIdle').value = originalConfig.maxIdle || '10';
                    document.getElementById('minIdle').value = originalConfig.minIdle || '5';
                    // 使用完整的图片解析API URL，不提取端口号
                    let apiValue = originalConfig.imageAnalysisApi || '';
                    document.getElementById('imageAnalysisApi').value = apiValue || 'http://127.0.0.1:50000';
                    
                    showMessage('表单已重置为当前配置', 'info');
                }
            }

            // 保存配置到历史记录
            function saveToHistory(config) {
                try {
                    // 从localStorage获取历史记录
                    let history = JSON.parse(localStorage.getItem('databaseConfigHistory') || '[]');
                    
                    // 创建配置摘要（不包含密码）
                    const configSummary = {
                        id: Date.now(),
                        driver: config.driver,
                        url: config.url,
                        username: config.username,
                        timestamp: new Date().toISOString(),
                        // 存储密码的哈希值而不是实际密码，提高安全性
                        passwordHash: config.password ? 'hashed' : ''
                    };
                    
                    // 添加到历史记录开头
                    history.unshift(configSummary);
                    
                    // 限制历史记录数量为5条
                    if (history.length > 5) {
                        history = history.slice(0, 5);
                    }
                    
                    // 保存回localStorage
                    localStorage.setItem('databaseConfigHistory', JSON.stringify(history));
                    
                    // 保存完整配置到sessionStorage（包含密码，但仅在会话期间有效）
                    sessionStorage.setItem(`dbConfig_${configSummary.id}`, JSON.stringify(config));
                    
                } catch (error) {
                    console.error('保存历史配置失败:', error);
                }
            }

            // 加载历史配置
            function loadHistoryConfigs() {
                try {
                    // 从localStorage获取历史记录
                    const history = JSON.parse(localStorage.getItem('databaseConfigHistory') || '[]');
                    
                    // 清空容器
                    recentConfigsDiv.innerHTML = '';
                    
                    if (history.length === 0) {
                        recentConfigsDiv.innerHTML = '<span class="text-sm text-gray-500">暂无历史记录</span>';
                        return;
                    }
                    
                    // 创建历史记录标签
                    history.forEach(config => {
                        const tag = document.createElement('div');
                        tag.className = 'bg-white px-3 py-2 rounded-md shadow-sm border border-gray-200 flex items-center text-sm cursor-pointer hover:bg-gray-50 transition-colors';
                        tag.title = `URL: ${config.url}\n用户名: ${config.username}\n时间: ${new Date(config.timestamp).toLocaleString()}`;
                        
                        // 提取数据库类型和主机名用于显示
                        const dbType = config.driver.split('.').pop().replace('Driver', '') || 'Unknown';
                        const hostMatch = config.url.match(/@([^:]+)/);
                        const host = hostMatch ? hostMatch[1] : 'unknown';
                        
                        tag.innerHTML = `
                            <i class="fa fa-database text-primary mr-2"></i>
                            <span class="font-medium">${dbType}</span>
                            <span class="mx-2 text-gray-400">•</span>
                            <span class="text-gray-600 truncate max-w-[100px]">${host}</span>
                            <span class="mx-2 text-gray-400">•</span>
                            <span class="text-gray-500 text-xs">${formatRelativeTime(config.timestamp)}</span>
                        `;
                        
                        // 添加点击事件，加载该配置
                        tag.addEventListener('click', function() {
                            loadConfigFromHistory(config.id);
                        });
                        
                        recentConfigsDiv.appendChild(tag);
                    });
                    
                } catch (error) {
                    console.error('加载历史配置失败:', error);
                    recentConfigsDiv.innerHTML = '<span class="text-sm text-gray-500">加载历史记录失败</span>';
                }
            }

            // 从历史记录加载配置
            function loadConfigFromHistory(configId) {
                try {
                    const configStr = sessionStorage.getItem(`dbConfig_${configId}`);
                    if (configStr) {
                        const config = JSON.parse(configStr);
                        
                        // 填充表单
                        document.getElementById('driver').value = config.driver || '';
                        document.getElementById('url').value = config.url || '';
                        document.getElementById('username').value = config.username || '';
                        document.getElementById('password').value = config.password || '';
                        document.getElementById('initialSize').value = config.initialSize || '5';
                        document.getElementById('maxActive').value = config.maxActive || '20';
                        document.getElementById('maxIdle').value = config.maxIdle || '10';
                        document.getElementById('minIdle').value = config.minIdle || '5';
                        document.getElementById('imageAnalysisApi').value = config.imageAnalysisApi || '';
                        
                        showMessage('已加载历史配置', 'info');
                    } else {
                        showMessage('该历史配置已过期', 'error');
                        loadHistoryConfigs(); // 刷新历史记录列表
                    }
                } catch (error) {
                    console.error('加载历史配置失败:', error);
                    showMessage('加载历史配置失败', 'error');
                }
            }

            // 格式化相对时间
            function formatRelativeTime(timestamp) {
                const now = new Date();
                const past = new Date(timestamp);
                const diffMs = now - past;
                const diffMins = Math.floor(diffMs / 60000);
                const diffHours = Math.floor(diffMins / 60);
                const diffDays = Math.floor(diffHours / 24);
                
                if (diffMins < 1) {
                    return '刚刚';
                } else if (diffMins < 60) {
                    return `${diffMins}分钟前`;
                } else if (diffHours < 24) {
                    return `${diffHours}小时前`;
                } else {
                    return `${diffDays}天前`;
                }
            }
        });
    </script>
    <!-- 登录弹窗 HTML -->
    <div id="loginModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-lg shadow-xl p-6 w-full max-w-md">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-xl font-bold text-gray-800">用户登录</h2>
                <button id="closeLoginModalBtn" class="text-gray-500 hover:text-gray-700 focus:outline-none">
                    <i class="fa fa-times text-xl"></i>
                </button>
            </div>
            <form id="loginForm" class="space-y-4">
                <div>
                    <label for="loginUsername" class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                    <input type="text" id="loginUsername" name="username" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="请输入用户名" required>
                </div>
                <div>
                    <label for="loginPassword" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                    <input type="password" id="loginPassword" name="password" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="请输入密码" required>
                </div>
                <div class="flex items-center justify-between">
                    <div class="flex items-center">
                        <input type="checkbox" id="rememberMe" name="rememberMe" class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
                        <label for="rememberMe" class="ml-2 block text-sm text-gray-700">记住我</label>
                    </div>
                    <a href="#" class="text-sm text-blue-600 hover:text-blue-800">忘记密码?</a>
                </div>
                <button type="submit" class="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                    登录
                </button>
            </form>
        </div>
    </div>
    <!-- 登录弹窗样式 -->
    <style>
        /* 登录按钮样式 */
        .login-button {
            background-color: #1E40AF;
            color: white;
            border: none;
            padding: 0.5rem 1rem;
            border-radius: 0.25rem;
            cursor: pointer;
            transition: background-color 0.2s;
        }
        
        .login-button:hover {
            background-color: #1E3A8A;
        }
        
        /* 侧边栏项样式 */
        .sidebar-item {
            display: flex;
            align-items: center;
            padding: 0.75rem 1rem;
            color: #6B7280;
            transition: all 0.2s;
            border-radius: 0.375rem;
            text-decoration: none;
        }
        
        .sidebar-item:hover {
            background-color: #F3F4F6;
            color: #1F2937;
        }
        
        .sidebar-item.active {
            background-color: #3B82F6;
            color: white;
        }
        
        .sidebar-item i {
            margin-right: 0.5rem;
            width: 1.5rem;
            text-align: center;
        }
    </style>
    <!-- 登录弹窗交互脚本 -->
    <script>
        // 点击登录按钮跳转到登录页面
        document.getElementById('showLoginModalBtn')?.addEventListener('click', function() {
            window.location.href = '/login.html';
        });
        
        // 关闭登录弹窗
        document.getElementById('closeLoginModalBtn')?.addEventListener('click', function() {
            document.getElementById('loginModal').classList.add('hidden');
        });
        
        // 点击弹窗外部关闭弹窗
        document.getElementById('loginModal')?.addEventListener('click', function(e) {
            if (e.target === this) {
                this.classList.add('hidden');
            }
        });
        
        // 登录表单提交
        document.getElementById('loginForm')?.addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 模拟登录成功
            const username = document.getElementById('loginUsername').value;
            
            // 存储登录状态到本地存储
            localStorage.setItem('isLoggedIn', 'true');
            localStorage.setItem('username', username);
            
            // 关闭弹窗
            document.getElementById('loginModal').classList.add('hidden');
            
            // 更新UI显示
            updateLoginUI();
            
            // 显示登录成功提示
            alert('登录成功！');
        });
        
        // 退出登录功能
        document.getElementById('logoutLink')?.addEventListener('click', function(e) {
            e.preventDefault();
            
            // 清除登录状态
            localStorage.removeItem('isLoggedIn');
            localStorage.removeItem('username');
            
            // 更新UI显示
            updateLoginUI();
            
            // 显示退出成功提示
            alert('退出成功！');
        });
        
        // 更新登录UI状态
        function updateLoginUI() {
            const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
            const username = localStorage.getItem('username');
            
            // 更新登录按钮显示
            const loginButton = document.getElementById('showLoginModalBtn');
            
            // 更新退出登录项显示
            const logoutItem = document.querySelector('.logout-item');
            
            if (isLoggedIn) {
                if (loginButton) {
                    loginButton.style.display = 'none';
                }
                if (logoutItem) {
                    logoutItem.classList.remove('hidden');
                }
            } else {
                if (loginButton) {
                    loginButton.style.display = 'block';
                }
                if (logoutItem) {
                    logoutItem.classList.add('hidden');
                }
            }
        }
        
        // 页面加载时检查登录状态
        document.addEventListener('DOMContentLoaded', function() {
            updateLoginUI();
        });
    </script>
</body>

</html>